﻿using PagedList;
using PagedList.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GiaoTrinhEPU.Repositories.Repositories;
using GiaoTrinhEPU.Repositories.DataModels;
using GiaoTrinhEPU.Repositories;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Core.ActionResults;
using GiaoTrinhEPU.Core;

namespace GiaoTrinhEPU.Areas.Manager.Controllers
{
    public class SyllabusController : BaseController
    {
        /// <summary>
        /// Declare Syllabus Repository
        /// </summary>
        private SyllabusRepository syllabusRepository;

        /// <summary>
        ///  Declare Session
        /// </summary>
        public static string SessionSyllabusSort = "SessionSyllabusSort";
        public static string SessionSyllabusSearch = "SessionSyllabusSearch";
        public static string SessionSyllabusSortOpt = "SessionSyllabusSortOpt";



        // GET: /Syllabus/
        /// <summary>
        /// Constructor that allow to create a Comment controller
        /// </summary>
        public SyllabusController()
            : base()
        {
            this.syllabusRepository = new SyllabusRepository();
            ViewBag.SelectedMenuId = 25;
        }

        public ActionResult Index(int page = 1, int size = 25, String search = "", String opt = "", String sort = "")
        {
            ViewBag.Title = "Giáo Trình";
            // Stored Session
           
            Session[SessionSyllabusSort] = sort.Trim().Length > 0 ? sort.ToLower() : Session[SessionSyllabusSort];
            Session[SessionSyllabusSortOpt] = opt.Trim().Length > 0 ? opt.ToLower() : Session[SessionSyllabusSortOpt];

            var syllabus = this.syllabusRepository.ListSyllabus(false).ToList();

            // Search
            if (Session[SessionSyllabusSearch] != null)
            {
                ViewBag.Keyword = Session[SessionSyllabusSearch].ToString();

                syllabus = syllabus.Where(l => l.Name.ToUpper().Contains(ViewBag.Keyword.ToUpper())).ToList();

            }
            // Sort 
            ViewBag.SortNameOpt = "desc";
            if (Session[SessionSyllabusSort] != null)
            {
                switch (Session[SessionSyllabusSort].ToString())
                {
                    case "name":
                        syllabus = Session[SessionSyllabusSortOpt].ToString().Equals("desc") ? syllabus.OrderByDescending(s => s.Name).ToList() : syllabus.OrderBy(s => s.Name).ToList();

                        Session[SessionSyllabusSort] = "name";
                        ViewBag.SortNameOpt = Sort.SetSortOrderOption(Session[SessionSyllabusSortOpt].ToString());
                        break;

                    default:
                        break;
                }
            }


            return View(syllabus.ToPagedList(page, size));
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            var syllabusModel = new SyllabusModel();
            syllabusModel.CreatedBy = User.Identity.Name;
            syllabusModel.CreatedDate = DateTime.Now;
            syllabusModel.ModifiedDate = syllabusModel.CreatedDate;

            this.PopulateDegreeDropDownList(syllabusModel.DegreeId);
            this.PopulateLevelDropDownList(syllabusModel.LevelId);
            this.PopulateDepartmentDropDownList(syllabusModel.DepartmentId);
            this.PopulatePublisherDropDownList(syllabusModel.PublisherId);
            return View(syllabusModel);
        }
        /// <summary>
        /// create action with param
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(SyllabusAuthorModelParent model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Create");
            }
            else
            {
                if (this.syllabusRepository.HasNameExisted(model.SyllabusModel.Name) == true)
                {
                    return View("Create").WithErrorMessage("Tên giáo trình đã được sử dụng");
                }


                var syllabus = new Syllabus();
                syllabus.Id = (int)model.SyllabusModel.Id;
                syllabus.Name = model.SyllabusModel.Name;
                syllabus.Code = model.SyllabusModel.Code;
                syllabus.PublisherId = model.SyllabusModel.PublisherId;
                syllabus.DegreeId = model.SyllabusModel.DegreeId;
                syllabus.LevelId = model.SyllabusModel.LevelId;
                syllabus.DepartmentId = model.SyllabusModel.DepartmentId;
                syllabus.NPage = (int)model.SyllabusModel.NPage;
                syllabus.NChapter = (int)model.SyllabusModel.NChapter;
                syllabus.Price = (int)model.SyllabusModel.Price;
                syllabus.CreatedBy = model.SyllabusModel.CreatedBy;
                syllabus.CreatedDate = model.SyllabusModel.CreatedDate;
                syllabus.ModifiedCount = (byte)(model.SyllabusModel.ModifiedCount+1);
                syllabus.ModifiedDate = model.SyllabusModel.ModifiedDate;
                syllabus.ModifiedBy = model.SyllabusModel.ModifiedBy;
                syllabus.Description = model.SyllabusModel.Description;

                this.syllabusRepository.CreateSyllabus(syllabus);
                // Returns view with successful message
                return RedirectToAction("Index").WithSuccessMessage("Đã tạo thành công giáo trình mới"); ;
            }
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            ViewBag.EnabledMenu = false;
            
            var syllabus = this.syllabusRepository.GetSyllabusById(id);
            var syllabusModel = new SyllabusModel(syllabus);
            syllabusModel.ModifiedBy = User.Identity.Name;
            syllabusModel.ModifiedDate = DateTime.Now;

            // population dropdow list
            this.PopulateDegreeDropDownList(syllabusModel.DegreeId);
            this.PopulateLevelDropDownList(syllabusModel.LevelId);
            this.PopulateDepartmentDropDownList(syllabusModel.DepartmentId);
            this.PopulatePublisherDropDownList(syllabusModel.PublisherId);
            return View(syllabusModel);
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(SyllabusModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Edit");
            }
            else
            {
                if (this.syllabusRepository.HasNameDuplicated(model.Id, model.Name) == true)
                {
                    return View("Edit").WithErrorMessage("Tên nhà xuất bản đã được sử dụng");
                }

                var syllabus = new Syllabus();

                syllabus.Id = (int)model.Id;
                syllabus.Name = model.Name;
                syllabus.Code = model.Code;
                syllabus.PublisherId = model.PublisherId;
                syllabus.DegreeId = model.DegreeId;
                syllabus.LevelId = model.LevelId;
                syllabus.PublisherId = model.PublisherId;
                syllabus.NPage = (int)model.NPage;
                syllabus.NChapter = (int)model.NChapter;
                syllabus.CreatedBy = model.CreatedBy;
                syllabus.CreatedDate = model.CreatedDate;
                syllabus.ModifiedCount = (byte)model.ModifiedCount;
                syllabus.ModifiedDate = model.ModifiedDate;
                syllabus.ModifiedBy = model.ModifiedBy;
                syllabus.Description = model.Description;

                this.syllabusRepository.UpdateSyllabus(syllabus);

                return RedirectToAction("Index").WithSuccessMessage("Đã sửa thành công nhà xuất bản này");

            }
        }
        /// <summary>
        /// Delete action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(int id)
        {
            this.syllabusRepository.DeleteSyllabus(id);
            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công nhà xuất bản này"); ;
        }

        /// <summary>
        ///  Delete Multi
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DeleteMulti(int[] ids = null)
        {
            if (ids == null || ids.Length == 0)
            {
                return RedirectToAction("Index");
            }

            for (int i = 0; i < ids.Length; i++)
            {
                int id = ids[i];

                this.syllabusRepository.DeleteSyllabus(id);
            }

            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công những nhà xuất bản này");
        }
        /// <summary>
        /// Clear
        /// </summary>
        /// <returns></returns>
        public ActionResult Clear()
        {
            // Clear sessions
            Session[SessionSyllabusSearch] = null;
            Session[SessionSyllabusSort] = null;
            Session[SessionSyllabusSortOpt] = null;

            return RedirectToAction("Index");
        }
        /// <summary>
        /// check name avaiable
        /// </summary>
        /// <param name="name"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult IsNameAvaiable(String name, int Id = 0)
        {
            if (Id == 0)
            {
                if (!this.syllabusRepository.HasNameExisted(name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (!this.syllabusRepository.HasNameDuplicated(Id, name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }


            }

            return Json("Tên nhà xuất bản đã được sử dụng", JsonRequestBehavior.AllowGet);
        }
    }
}
